// import type { Stats } from 'node:fs'
// const { fs, path } = window.electronAPI
import { format } from '@/utils/date'
import chokidar, { ChokidarOptions } from 'chokidar'
import fsSync from 'node:fs'
import fs from 'node:fs/promises'
import path from 'node:path'

/**
 * 文件信息
 */
export interface IFileItem {
    /** 文件名 */
    name: string
    /** 路径 */
    path: string
    /** 文件大小 */
    size: number
    /** 是否是文件夹 */
    isDir: boolean
    /** 是否是文件 */
    isFile: boolean
    /** 文件后缀名 */
    extWithDot: string
    /** 文件后缀名 */
    ext: string
    /** 文件创建时间 */
    createTime: string
    /** 文件修改时间 */
    updateTime: string
    /** 文件访问时间 */
    accessTime: string
    /** 是否是隐藏文件 */
    isHidden: boolean
}

/** 获取文件信息 */
export const stats = async (filePath: string) => {
    const stat = await fs.stat(filePath)
    const filename = path.basename(filePath)
    const result: IFileItem = {
        name: filename,
        path: filePath,
        isDir: stat.isDirectory(),
        isFile: stat.isFile(),
        size: stat.isFile() ? stat.size : 0,
        ext: path.extname(filename).substring(1),
        extWithDot: path.extname(filename),
        createTime: format(stat.birthtime),
        updateTime: format(stat.mtime),
        accessTime: format(stat.atime),
        /** TODO: win下隐藏文件不能这样判断 */
        isHidden: filename.startsWith('.')
    }
    return result
}

/**
 * 读取文件夹下的所有文件
 * @param dirPath 文件夹路径
 * @returns
 */
export const readDir = async (dirPath: string) => {
    const fileList = await fs.readdir(dirPath)
    const res: IFileItem[] = []
    const proms = fileList.map(async (filename) => {
        const filePath = await path.join(dirPath, filename)
        const stat = await stats(filePath)
        res.push(stat)
    })
    await Promise.all(proms)
    return res
}

/** 监听目录内容变化 */
export const watchDir = (dirPath: string, _options?: ChokidarOptions) => {
    try {
        let watcher = chokidar.watch(dirPath, {
            depth: 0
        })
        return watcher
    } catch (error) {
        console.log(error)
    }
}

/**
 * 复制文件
 */
export const copyFile = async (srcPath: string, destPath: string, overwrite = false) => {
    if (overwrite) {
        await fs.unlink(destPath)
    }
    return await fs.copyFile(srcPath, destPath, fs.constants.COPYFILE_EXCL)
}

/**
 * 移动文件
 */
export const moveFile = async (srcPath: string, destPath: string) => {
    return await fs.rename(srcPath, destPath)
}

/**
 * 删除文件
 */
export const deleteFile = async (filePath: string) => {
    return await fs.unlink(filePath)
}

/**
 * 读取json文件
 * @param filePath 文件路径
 * @returns json对象
 */
export const readJson = (filePath: string) => {
    return JSON.parse(fsSync.readFileSync(filePath, 'utf-8'))
}

/**
 * 写入json文件
 * @param filePath 文件路径
 * @param data json对象
 */
export const writeJson = (filePath: string, data: any) => {
    fsSync.writeFileSync(filePath, JSON.stringify(data, null, 4), 'utf-8')
}
